import 'package:flutter/material.dart';
import '../utils/responsive_layout.dart';
import '../theme/app_theme.dart';
import 'modern_button.dart';

/**
 * 现代化导航项配置
 */
class ModernNavigationItem {
  final String label;
  final IconData icon;
  final IconData? activeIcon;
  final String? tooltip;
  final VoidCallback? onTap;
  final bool enabled;
  final Widget? badge;

  const ModernNavigationItem({
    required this.label,
    required this.icon,
    this.activeIcon,
    this.tooltip,
    this.onTap,
    this.enabled = true,
    this.badge,
  });
}

/**
 * 现代化底部导航栏
 */
class ModernBottomNavigation extends StatefulWidget {
  final List<ModernNavigationItem> items;
  final int currentIndex;
  final ValueChanged<int>? onTap;
  final Color? backgroundColor;
  final Color? selectedItemColor;
  final Color? unselectedItemColor;
  final bool showLabels;
  final double? elevation;

  const ModernBottomNavigation({
    super.key,
    required this.items,
    this.currentIndex = 0,
    this.onTap,
    this.backgroundColor,
    this.selectedItemColor,
    this.unselectedItemColor,
    this.showLabels = true,
    this.elevation,
  });

  @override
  State<ModernBottomNavigation> createState() => _ModernBottomNavigationState();
}

class _ModernBottomNavigationState extends State<ModernBottomNavigation>
    with TickerProviderStateMixin {
  late List<AnimationController> _animationControllers;
  late List<Animation<double>> _scaleAnimations;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  @override
  void dispose() {
    for (final controller in _animationControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  /**
   * 初始化动画
   */
  void _initAnimations() {
    _animationControllers = List.generate(
      widget.items.length,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 200),
        vsync: this,
      ),
    );

    _scaleAnimations = _animationControllers
        .map((controller) => Tween<double>(
              begin: 1.0,
              end: 1.2,
            ).animate(CurvedAnimation(
              parent: controller,
              curve: Curves.easeInOut,
            )))
        .toList();

    // 初始选中项动画
    if (widget.currentIndex < _animationControllers.length) {
      _animationControllers[widget.currentIndex].forward();
    }
  }

  @override
  void didUpdateWidget(ModernBottomNavigation oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 更新选中项动画
    if (oldWidget.currentIndex != widget.currentIndex) {
      if (oldWidget.currentIndex < _animationControllers.length) {
        _animationControllers[oldWidget.currentIndex].reverse();
      }
      if (widget.currentIndex < _animationControllers.length) {
        _animationControllers[widget.currentIndex].forward();
      }
    }
  }

  /**
   * 处理点击事件
   */
  void _handleTap(int index) {
    if (!widget.items[index].enabled) return;
    
    widget.onTap?.call(index);
    widget.items[index].onTap?.call();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    return Container(
      decoration: BoxDecoration(
        color: widget.backgroundColor ?? colorScheme.surface,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: widget.elevation ?? 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Container(
          height: isDesktop ? 72 : 64,
          padding: EdgeInsets.symmetric(
            horizontal: isDesktop ? 24 : 16,
            vertical: isDesktop ? 12 : 8,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: widget.items.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              final isSelected = index == widget.currentIndex;

              return Expanded(
                child: _buildNavigationItem(
                  context,
                  item,
                  index,
                  isSelected,
                  theme,
                  colorScheme,
                  isDesktop,
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }

  /**
   * 构建导航项
   */
  Widget _buildNavigationItem(
    BuildContext context,
    ModernNavigationItem item,
    int index,
    bool isSelected,
    ThemeData theme,
    ColorScheme colorScheme,
    bool isDesktop,
  ) {
    final selectedColor = widget.selectedItemColor ?? colorScheme.primary;
    final unselectedColor = widget.unselectedItemColor ?? colorScheme.onSurfaceVariant;
    final color = isSelected ? selectedColor : unselectedColor;

    return AnimatedBuilder(
      animation: _scaleAnimations[index],
      builder: (context, child) {
        return GestureDetector(
          onTap: () => _handleTap(index),
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: isDesktop ? 12 : 8,
              vertical: isDesktop ? 8 : 6,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 图标和徽章
                Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Transform.scale(
                      scale: _scaleAnimations[index].value,
                      child: Icon(
                        isSelected && item.activeIcon != null
                            ? item.activeIcon!
                            : item.icon,
                        color: color,
                        size: isDesktop ? 24 : 22,
                      ),
                    ),
                    if (item.badge != null)
                      Positioned(
                        right: -8,
                        top: -8,
                        child: item.badge!,
                      ),
                  ],
                ),
                
                // 标签
                if (widget.showLabels) ...[
                  const SizedBox(height: 4),
                  Text(
                    item.label,
                    style: theme.textTheme.bodySmall?.copyWith(
                      color: color,
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ],
            ),
          ),
        );
      },
    );
  }
}

/**
 * 现代化侧边导航栏
 */
class ModernSideNavigation extends StatefulWidget {
  final List<ModernNavigationItem> items;
  final int currentIndex;
  final ValueChanged<int>? onTap;
  final Color? backgroundColor;
  final Color? selectedItemColor;
  final Color? unselectedItemColor;
  final bool extended;
  final double? width;
  final Widget? header;
  final Widget? footer;

  const ModernSideNavigation({
    super.key,
    required this.items,
    this.currentIndex = 0,
    this.onTap,
    this.backgroundColor,
    this.selectedItemColor,
    this.unselectedItemColor,
    this.extended = true,
    this.width,
    this.header,
    this.footer,
  });

  @override
  State<ModernSideNavigation> createState() => _ModernSideNavigationState();
}

class _ModernSideNavigationState extends State<ModernSideNavigation>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _widthAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _widthAnimation = Tween<double>(
      begin: 72,
      end: widget.width ?? 280,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    if (widget.extended) {
      _animationController.forward();
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(ModernSideNavigation oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    if (oldWidget.extended != widget.extended) {
      if (widget.extended) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    }
  }

  /**
   * 处理点击事件
   */
  void _handleTap(int index) {
    if (!widget.items[index].enabled) return;
    
    widget.onTap?.call(index);
    widget.items[index].onTap?.call();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return AnimatedBuilder(
      animation: _widthAnimation,
      builder: (context, child) {
        return Container(
          width: _widthAnimation.value,
          decoration: BoxDecoration(
            color: widget.backgroundColor ?? colorScheme.surface,
            border: Border(
              right: BorderSide(
                color: colorScheme.outline.withOpacity(0.1),
                width: 1,
              ),
            ),
          ),
          child: Column(
            children: [
              // 头部
              if (widget.header != null)
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(16),
                  child: widget.header!,
                ),

              // 导航项
              Expanded(
                child: ListView.builder(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  itemCount: widget.items.length,
                  itemBuilder: (context, index) {
                    final item = widget.items[index];
                    final isSelected = index == widget.currentIndex;

                    return _buildNavigationItem(
                      context,
                      item,
                      index,
                      isSelected,
                      theme,
                      colorScheme,
                    );
                  },
                ),
              ),

              // 底部
              if (widget.footer != null)
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(16),
                  child: widget.footer!,
                ),
            ],
          ),
        );
      },
    );
  }

  /**
   * 构建导航项
   */
  Widget _buildNavigationItem(
    BuildContext context,
    ModernNavigationItem item,
    int index,
    bool isSelected,
    ThemeData theme,
    ColorScheme colorScheme,
  ) {
    final selectedColor = widget.selectedItemColor ?? colorScheme.primary;
    final unselectedColor = widget.unselectedItemColor ?? colorScheme.onSurfaceVariant;
    final color = isSelected ? selectedColor : unselectedColor;
    final backgroundColor = isSelected 
        ? colorScheme.primaryContainer.withOpacity(0.3)
        : Colors.transparent;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      child: Material(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(12),
        child: InkWell(
          onTap: () => _handleTap(index),
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              children: [
                // 图标和徽章
                Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Icon(
                      isSelected && item.activeIcon != null
                          ? item.activeIcon!
                          : item.icon,
                      color: color,
                      size: 24,
                    ),
                    if (item.badge != null)
                      Positioned(
                        right: -8,
                        top: -8,
                        child: item.badge!,
                      ),
                  ],
                ),
                
                // 标签
                if (widget.extended) ...[
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      item.label,
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: color,
                        fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }
}

/**
 * 现代化标签导航栏
 */
class ModernTabNavigation extends StatefulWidget {
  final List<ModernNavigationItem> items;
  final int currentIndex;
  final ValueChanged<int>? onTap;
  final Color? backgroundColor;
  final Color? selectedItemColor;
  final Color? unselectedItemColor;
  final Color? indicatorColor;
  final bool isScrollable;
  final EdgeInsetsGeometry? padding;

  const ModernTabNavigation({
    super.key,
    required this.items,
    this.currentIndex = 0,
    this.onTap,
    this.backgroundColor,
    this.selectedItemColor,
    this.unselectedItemColor,
    this.indicatorColor,
    this.isScrollable = false,
    this.padding,
  });

  @override
  State<ModernTabNavigation> createState() => _ModernTabNavigationState();
}

class _ModernTabNavigationState extends State<ModernTabNavigation>
    with TickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: widget.items.length,
      vsync: this,
      initialIndex: widget.currentIndex,
    );
    
    _tabController.addListener(_handleTabChange);
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(ModernTabNavigation oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    if (oldWidget.currentIndex != widget.currentIndex) {
      _tabController.animateTo(widget.currentIndex);
    }
  }

  /**
   * 处理标签变化
   */
  void _handleTabChange() {
    if (_tabController.indexIsChanging) return;
    
    final index = _tabController.index;
    widget.onTap?.call(index);
    widget.items[index].onTap?.call();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    return Container(
      decoration: BoxDecoration(
        color: widget.backgroundColor ?? colorScheme.surface,
        border: Border(
          bottom: BorderSide(
            color: colorScheme.outline.withOpacity(0.1),
            width: 1,
          ),
        ),
      ),
      child: TabBar(
        controller: _tabController,
        isScrollable: widget.isScrollable,
        padding: widget.padding,
        labelColor: widget.selectedItemColor ?? colorScheme.primary,
        unselectedLabelColor: widget.unselectedItemColor ?? colorScheme.onSurfaceVariant,
        indicatorColor: widget.indicatorColor ?? colorScheme.primary,
        indicatorWeight: 3,
        indicatorSize: TabBarIndicatorSize.label,
        labelStyle: theme.textTheme.bodyMedium?.copyWith(
          fontWeight: FontWeight.w600,
        ),
        unselectedLabelStyle: theme.textTheme.bodyMedium,
        tabs: widget.items.map((item) {
          return Tab(
            icon: Stack(
              clipBehavior: Clip.none,
              children: [
                Icon(item.icon, size: isDesktop ? 24 : 22),
                if (item.badge != null)
                  Positioned(
                    right: -8,
                    top: -8,
                    child: item.badge!,
                  ),
              ],
            ),
            text: item.label,
          );
        }).toList(),
      ),
    );
  }
}